#include <iostream>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include "Geo.h"
#include "Shader.h"

GLFWwindow *window;

void initGl();

void framebuffer_size_callback(GLFWwindow *window, int width, int height);
void processInput(GLFWwindow *w);

int main(void)
{

	initGl();
	Shader shader("../assets/shader/vertex.glsl", "../assets/shader/fragment.glsl");

	Geometry *geo = new GeoBox();

	while (!glfwWindowShouldClose(window))
	{
		processInput(window);
		glClearColor(0.2, 0.3, 0.3, 1.0);
		glClear(GL_COLOR_BUFFER_BIT);

		shader.bind();
		geo->bind();

		glDrawElements(GL_TRIANGLES, geo->count(), GL_UNSIGNED_INT, 0);

		glfwSwapBuffers(window);
		glfwPollEvents();
	}
	delete geo;
	glfwTerminate(); //回收资源
	return 0;
}

void framebuffer_size_callback(GLFWwindow *window, int width, int height)
{
	glViewport(0, 0, width, height);
}
void processInput(GLFWwindow *w)
{
	if (glfwGetKey(w, GLFW_KEY_ESCAPE) == GLFW_PRESS)
		glfwSetWindowShouldClose(w, true);
}

void initGl()
{
	glfwInit();
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	window = glfwCreateWindow(800, 600, "glStudy", nullptr, nullptr);
	if (!window)
	{
		std::cout << "create window fail";
		glfwTerminate();
	}
	glfwMakeContextCurrent(window);
	if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
	{
		std::cout << "Failed to initialize GLAD" << std::endl;
		glfwTerminate();
	}
	glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
}
